define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {

            layui.use(['table','upload','form'], function(){
                var table = layui.table;
                upload = layui.upload;

                table.render({
                    elem: '#table'
                    ,url:'kuerp/area/index'
                    ,parseData: function(res){
                        return {
                            "code": 0,
                            "msg": '',
                            "count": res.total,
                            "data": res.rows
                         };
                    }
                    ,toolbar: '#thisToolbar'
                    ,defaultToolbar: ''
                    ,page: {
                        prev: __('Previous'),
                        next: __('Next'),
                        first: __('First'),
                        last: __('Last'),
                        skipText: [__('Go to page'), '', __('Confirm')],
                        countText: [__('Total') + ' ',' ' +  __('Records')],
                        limitTemplet: function(item) {
                            return item + ' ' + __('entries');
                          }
                    }
                    ,text: {
                        none: __('No data'),
                        loading: __('Loading...'),
                    }
                    ,limit: 20  // 每页显示20条数据
                    ,cellMinWidth: 100
                    ,cols: [[
                        {checkbox: true},
                        {field: 'id', title: 'ID', width: 80},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        // {field: 'shortname', title: __('Shortname'), operate: 'LIKE'},
                        {field: 'level', title: __('Level'), width: 100},
                        {field: 'pid', title: 'PID', width: 100},
                        // {field: 'adcode', title: 'Adcode', width: 120},
                        // {field: 'lng', title: 'Lng', width: 120},
                        // {field: 'lat', title: 'Lat', width: 120},
                        {fixed: 'right', title: __('Operate'), toolbar: '#rowToolbar', width: 160}
                    ]]
                });

                table.on('toolbar(table)', function(obj){
                    switch(obj.event){
                        case 'refresh':
                            table.reload('table', []);
                            break;
                        case 'add':
                            Fast.api.open('kuerp/area/add', __('Add'));
                            break;
                    }
                });

                table.on('tool(table)', function(obj){
                    var data = obj.data;
                    if (obj.event === 'edit') {
                        Fast.api.open('kuerp/area/edit?ids=' + encodeURIComponent(data.id), __('Edit'), {
                            callback: function(){ table.reload('table', []); }
                        });
                    }
                });

                //搜索事件
                $('#search').on('click', function () {
                    table.reload('table', {
                        where: {
                            filter:JSON.stringify(getSearch()),
                            op:JSON.stringify(getOp()),
                        }
                        ,text: {
                            none: __('No data'),
                            loading: __('Loading...'),
                        }
                        ,page: {
                            curr: 1,
                            prev: __('Previous'),
                            next: __('Next'),
                            first: __('First'),
                            last: __('Last'),
                            skipText: [__('Go to page'), '', __('Confirm')],
                            countText: [__('Total') + ' ',' ' +  __('Records')],
                            limitTemplet: function(item) {
                                return item + ' ' + __('entries');
                            }
                        }
                    });
                });

                function getSearch() {
                    var search = {};
                    var name = $('#name').val();
                    if(name!=''){
                        search.name = name;
                    }
                    var level = $('#level').val();
                    if(level!=''){
                        search.level = level;
                    }
                    return search;
                }
                function getOp() {
                    var op = {};
                    op.name = 'LIKE';
                    return op;
                }
            });
            Controller.api.bindevent();
        },

        add: function () {
            Controller.api.mountPidByLevel();
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.mountPidByLevel($('#c-pid').val(), $('#c-level').val());
            Controller.api.bindevent();
        },
        api: {
            mountPidByLevel: function(selectedPid, currentLevel){
                var fillOptions = function(items){
                    var $sel = $('#c-pid');
                    $sel.empty();
                    $sel.append('<option value="0">Top</option>');
                    for (var i=0;i<items.length;i++){
                        var it = items[i];
                        var sel = (selectedPid && (selectedPid == it.id)) ? ' selected' : '';
                        $sel.append('<option value="'+ it.id +'"'+ sel +'>'+ (it.name || ('#'+it.id)) +'</option>');
                    }
                };
                var loadFor = function(level){
                    if (!level || level <= 1){ fillOptions([]); return; }
                    $.get('kuerp/area/parents?level=' + encodeURIComponent(level - 1), function(res){
                        var list = (res && res.data) ? res.data : [];
                        fillOptions(list);
                    });
                };
                // 初次
                var lvl = currentLevel ? parseInt(currentLevel) : parseInt($('#c-level').val());
                loadFor(lvl);
                // 监听 level 变化
                $('#c-level').off('change._pid').on('change._pid', function(){
                    selectedPid = 0;
                    loadFor(parseInt(this.value));
                });
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function(){
                    Fast.api.close();
                    // 刷新列表
                    if (typeof table !== 'undefined') {
                        table.reload('table', []);
                    }
                });
            }
        }
    };
    return Controller;
});


